package cn.wolfcode.shop.cloud.mq.listener;

import cn.wolfcode.shop.cloud.common.JSONUtil;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.core.WebSocketServer;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;

/**
 * Created by wolfcode-lanxw
 */
@Slf4j
@Getter
abstract class AbstractResultNotifyMQListener {

    private String logTag = "[客户端通知]";

    void sendMessage(String uuid, Result<?> result) {
        try {
            // 根据经uuid找到对应的客户端
            // 最大重试次数
            int max_retries = 3;
            Session session = null;
            do {
                session = WebSocketServer.clients.get(uuid);
                if (session == null) {
                    // 如果当前获取不到才睡500毫秒
                    Thread.sleep(500);
                }
                // 重试次数-1
                max_retries--;
            } while (session == null && max_retries >= 0);

            if (session != null) {
                // 包装result对象, 转换成json格式
                // 发送给前端
                session.getBasicRemote().sendText(JSONUtil.toJSONString(result));
            } else {
                log.warn("{} 通知前端消息失败, 无法获取到用户:{}的连接", getLogTag(), uuid);
            }
        } catch (Exception e) {
            log.error(logTag + " 通知前端消息失败", e);
        }
    }
}
